<template>
  <el-form
    ref="editFormRef"
    :model="editData"
    :rules="menuFormRules"
    label-width="auto"
    style="max-width: 600px"
  >
    <el-form-item label="角色名称" prop="name">
      <el-input v-model="editData.name" />
    </el-form-item>
    <el-form-item label="描述" prop="description">
      <el-input v-model="editData.description" />
    </el-form-item>
    <el-form-item label="是否是默认角色 " prop="is_default">
      <el-switch
        v-model="editData.is_default"
        :active-value="1"
        :inactive-value="0"
      ></el-switch>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm" :loading="loading"
        >提交</el-button
      >
      <el-button @click="handleReset">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { IRole } from "@/api/role"
import { PropType } from "vue"
import { FormInstance } from "element-plus"

const editData = ref({
  name: "",
  description: "",
  is_default: 0
})
// 验证规则
const menuFormRules = {
  name: {
    required: true,
    message: "请输⼊⻆⾊名称",
    trigger: "blur"
  },
  description: {
    required: true,
    message: "请输⼊说明",
    trigger: "blur"
  }
}
const { data } = defineProps({
  data: {
    type: Object as PropType<IRole>,
    default: () => ({})
  }
})
// 用于做默认值
// const defaultProps = {
//   name: "",
//   description: "",
//   is_default: 0
// }
// const resetForm = () => {
//   editData.value = { ...defaultProps, ...data }
// }
const editFormRef = ref()
const resetForm = () => {
  editFormRef.value?.clearValidate()
  editData.value = { ...data }
}
watchEffect(() => {
  resetForm()
})
const emit = defineEmits(["submit"])
const loading = ref(false)
const submitForm = () => {
  if (loading.value) return // 防⽌重复提交
  loading.value = true
  ;(editFormRef.value as FormInstance).validate((valid) => {
    if (valid) {
      emit("submit", editData.value)
    }
    loading.value = false
  })
}
const handleReset = () => {
  resetForm()
}
</script>
